<?php

/**
 * @Author: Wang chunsheng  email:2192138785@qq.com
 * @Date:   2023-04-24 13:54:59
 * @Last Modified by:   Wang chunsheng  email:2192138785@qq.com
 * @Last Modified time: 2023-05-26 15:52:53
 */

namespace Common;


use Hyperf\Context\Context;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Hyperf\HttpServer\Request;
use Hyperf\HttpServer\Response;


abstract class ApiController extends AbstractController
{
    /**
     * @Inject(RequestInterface::class)
     * @var Request
     */
    #[Inject]
    protected RequestInterface $request;

    /**
     * @Inject(ResponseInterface::class)
     * @var Response
     */
    #[Inject]
    protected ResponseInterface $response;


    /**
     * 不用进行签名验证的方法
     * 例如： ['index', 'update', 'create', 'view', 'delete']
     * 默认全部需要验证
     *
     * @var array
     */
    public  array $signOptional = [];


    protected function getAttribute($key)
    {
//        $request = Context::get(ServerRequestInterface::class);

        return $this->request->getAttribute($key);
    }

    public function writeJson($statusCode = 200, $result = null, $msg = null): array
    {
        if ($result && is_array($result) && key_exists('code', $result)) {
            // 服务中包含了状态，直接返回
            $data = $result;
        } else {
            $data = [
                'code' => $statusCode,
                'data' => $result,
                'message' => $msg,
            ];
        }

        return $data;
    }
}
